from django.shortcuts import render
from django.http import JsonResponse
from user.user_decoration import islogin
from .models import CartInfo
from user.models import UserInfo
from django.db.models import Sum
# Create your views here.



@islogin
#详情页添加购物车的ajax请求
def add(request):
    # post传过来两个参数,gid为商品对象id,nums为商品个数,还有就是用户user
    #首先需要判断用户
    # context = {}
    # return render(request, '')

    uid = request.session.get('uid')
    # user = UserInfo.objects.get(id=uid)
    dict = request.POST
    gid = int(dict['gid'])  #good对象
    nums = int(dict['nums'])
    # print(gid, nums, '-----------------------------')

    #判断该商品/用户是否在数据库存在,如果存在,则直接在原类型上添加
    cartinfos = CartInfo.objects.filter(user_id=uid,goods_id=gid)
    # count = cartinfo.count
    # print(count)
    maxcount = 1
    maxcountmsg = ''
    if cartinfos:
        # print(cartinfo.count)
        cartinfo = cartinfos[0]
        # count = cartinfo.count
        cartinfo.count += nums
        if cartinfo.count > 5:
            cartinfo.count = 5
            maxcount = 2
            maxcountmsg = '最多可添加5件商品'
        print(cartinfo.count)

    else:
        #存入数据库
        cartinfo = CartInfo()
        cartinfo.user_id = uid
        cartinfo.goods_id = gid
        cartinfo.count = nums

    #对count进行判断,如果>5,则为5,并返回提示
    # maxcount = ''
    # if cartinfo.count > 5:
    #     cartinfo.count = 5
    #     maxcount = '最多可添加5件商品'

    # 防止数据没存入数据库做个判断
    msg = ''
    cid = None
    try:
        cartinfo.save()
    except:
        status = 1
        msg = '加入购物车失败,请重试'
    else:
        cid = cartinfo.id
        status = 2


    #返回查询到的购物车的所有count
    # dict = BookInfo.objects.aggreagate(Sum('read'))  # 统计所有图书的的阅读量，此时dict的键为read__sum
    # return HttpResponse(dict['read__sum'])  # 返回得到的阅读量
    dict2 = CartInfo.objects.aggregate(Sum('count'))
    cart_num = dict2['count__sum']
    # print(cart_num)



    context = {'status':status,'cart_num':cart_num,'msg':msg,
               'maxcount':maxcount,'maxcountmsg':maxcountmsg,
               'cid':cid,}

    #todo  这里这个bug,当切换页面的时候,购物车显示数量为0
    return JsonResponse(context)


#
# @islogin
# #商品列表页加入购物车
# def addlist(request):
#     pass



#定义购物车页
@islogin
def cart(request):

    #取出当前用户的所有购物车信息
    uid = request.session.get('uid')

    # 这里返回的是一个购物车列表,可以通过遍历购物车列表,得到相应用户的商品信息和数量信息
    carts = CartInfo.objects.filter(user_id=uid)
    #总共有多少种商品,就遍历carts就好
    type_num = len(carts)

    context = {'carts':carts,'type_num':type_num,}
    return render(request,'cart/cart.html',context)


@islogin
#定义删除页
def cartdel(request):
    uid = request.session.get('uid')
    dict = request.POST
    context = {}
    try:
        cart_id = int(dict['id'])
        CartInfo.objects.get(id=cart_id).delete()
    except:
        context['isdelete'] = 1
    else:
        context['isdelete'] = 2

    return JsonResponse(context)


@islogin
#定义最右上角的购物车数量显示
def cartnum(request):
    # 取出当前用户的所有购物车信息
    uid = request.session.get('uid')

    # 这里返回的是一个购物车列表,可以通过遍历购物车列表,得到相应用户的商品信息和数量信息
    dict = CartInfo.objects.filter(user_id=uid).aggregate(Sum('count'))
    count = dict['count__sum']

    # if count == None:

    return JsonResponse({'count':count if count else 0})


@islogin
# 定义购物车页面中数量加减的函数
def changenum(request):
    dict = request.GET
    num = int(dict['num'])
    cid = int(dict['cid'])
    # print(gid,'---------------------')
    # uid = request.session.get('uid')
    # print(type(uid))
    cartinfo = CartInfo.objects.get(id=cid)
    # print(cartinfo)
    cartinfo.count = num
    context = {}
    try:
        cartinfo.save()
        context['status'] = 1
    except:
        context['status'] = 2
    return JsonResponse(context)




